#!/usr/bin/env python
# coding:utf-8
""" 
上下文，用于实现中间件功能
"""
# from router import Router
from middlewares.paramsVerifyMiddleware import ParamsVerifyMiddleware
from middlewares.tokenVerifyMiddleware import TokenVerifyMiddleware
from middlewares.websocketPackageMiddleware import WebsocketPackageMiddleware
from middlewares.logMiddleware import LogMiddleware
from middlewares.exceptionMiddleware import ExceptionMiddleware

class Context(object):

    def __init__(self,request,router,worker):
        self.request = request
        self.raw_request = request
        self.router = router
        self.worker = worker
        self._middlewares = []
        self._index = -1
        self.init_middlewares()

    def add_middleware(self,middleware):
        self._middlewares.append(middleware)
    
    def init_middlewares(self):
        self.add_middleware(WebsocketPackageMiddleware)
        self.add_middleware(ExceptionMiddleware)
        self.add_middleware(LogMiddleware)
        self.add_middleware(ParamsVerifyMiddleware)
        # self.add_middleware(TokenVerifyMiddleware)
    
    async def next(self):
        self._index += 1
        middleware_length = len(self._middlewares)
        if self._index < middleware_length:
            func = self._middlewares[self._index]
            return await func(self)            